# Create your views here.
#from django import render
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render, render_to_response
from django.shortcuts import redirect
from django.contrib import auth
from django.core.context_processors import csrf
from django.template import Context, RequestContext, loader
from theblog.models import Blog, Comments
from django.core.mail import send_mail
from theblog.forms import AuthorForm, CommentsForm, Blog
from django.contrib.auth.models import User
from datetime import date
import datetime

def home(request):
	c = {}
	c.update(csrf(request))
	return render_to_response("LoginPage.html", c)

def login_user(request):
	state = ''
	username = password = ''
	c = {}
	c.update(csrf(request))
	if request.POST:
		username = request.POST.get('username')
		password = request.POST.get('password')

		user = auth.authenticate(username=username, password=password)
		if user is not None and user.is_active:
			if user.is_active:	
				auth.login(request, user)
				request.session['user'] = username
				queryset = Blog.objects.all()
				return render_to_response("view.html", {'username':username, 'queryset':queryset}, context_instance=RequestContext(request))
	  		else:
				state = "Your account is not active"

				#return render_to_response("loginfailed.html",{'state':state}, context_instance=RequestContext(request))	
 		else:
			return redirect('/theblog/')

	return render_to_response('LoginPage.html', {'state':state, 'username':username}, context_instance=RequestContext(request))

def logout_user(request):
	auth.logout(request)
	return redirect('/theblog/')

	
def register(request):
	c = {}
	c.update(csrf(request))
	aform = AuthorForm()
	title = 'Registration Form'
	return render_to_response('registrationform.html', {'title':title, 'aform':aform}, context_instance=RequestContext(request))
	
def comments(request):
	c = {}
	c.update(csrf(request))
			
def registration(request):
	c = {}
	c.update(csrf(request))
	if request.method == 'POST':
		form = AuthorForm(request.POST)
		if form.is_valid():
			firstname = form.cleaned_data['firstname']
			lastname = form.cleaned_data['lastname']
			username =  form.cleaned_data['username']
			email =  form.cleaned_data['email']
			password =  form.cleaned_data['password1']			
			if User.objects.filter(username = username).count() == 1:
				state = "Username is taken already. Please choose a different username."
				return render_to_response("registrationform.html", {'state':state, 'form':form}, context_instance=RequestContext(request))			
			else:
				new_user = User.objects.create_user(username, email, password)
				new_user.save()	
				new_user.is_active = True				
				return render_to_response('edit_profile.html', {'new_user':new_user}, context_instance=RequestContext(request))
		else:
			return HttpResponse('Form not valid.')
	
	return render_to_response('auth.html', context_instance=RequestContext(request))

def createNewBlog(request):
	username = request.user
	return render_to_response("newblog.html", {'username':username}, context_instance=RequestContext(request))


def passwordpage(request):
	return render_to_response("resetpassword.html", context_instance=RequestContext(request))

def resetPwd(request):
	message = 'User does not exist'	
	if request.method == 'POST':
		username = request.POST.get('uname')
		password = request.POST.get('pwd')
		new_password = request.POST.get('newpwd')
		new_password2 = request.POST.get('newpwd2')
		if User.objects.filter(username=username).count == 0:	
			return render_to_response("LoginPage.html", {'message':message}, context_instance=RequestContext(request))
		else:
			u = User.objects.get(username__exact = username)
			u.set_password('new_password2')
			u.save()
			return redirect('/theblog/')
	else:
		message = 'Sorry! The username you provided does not exist.'
		return redirect('/theblog/')

def saveBlog(request):
	c = {}
	c.update(csrf(request))
	blog_title = ''
	blog_text = ''	
	date_published = datetime.datetime.now()
	if request.method == 'POST':		
		username = request.user		
		blog_title = request.POST.get('title')
		blog_text = request.POST.get('content')
		pubdate = date_published.strftime("%Y-%m-%d %H:%M:%S")
		comment_count = 0;		
		b = Blog(author = username, 
					blog_title = blog_title, 
					blog_text = blog_text,
					pubdate = pubdate,
					comment_count = comment_count)
		b.save()		
		blogs = Blog.objects.filter(author=username)
		return render_to_response("view.html", {'username':username, 'blogs':blogs}, context_instance=RequestContext(request))

#@login_required
def viewBlog(request):
	c = {}
	c.update(csrf(request))
	if request.user.is_authenticated():
			username = request.user
			blog_exists = Blog.objects.filter(author=username).count()
			if blog_exists == 0:
				message = 'You have not created any blogs yet. Start by writing a blog'
				return render_to_response("view.html", {'username':username, 'message':message}, context_instance=RequestContext(request))
			else:	
				blogs = Blog.objects.filter(author=username)			
			return render_to_response("view.html", {'username':username, 'blogs':blogs}, context_instance=RequestContext(request))
	else:
		return HttpResponse("Not a valid user")

def viewContent(request):
	blogname = ''
	username = request.user
	if blogname is None:
		return HttpResponse("Nothing to return.")	
	else:
		cc = []
		#data{}
		blogname = request.GET.get("blogname")
		b = Blog()
		c = Comments()
		row = b.getContent(blogname)
		content = row[0]
		pubdate = row[1]		
		comments_count = c.getNoOfComments(blogname)
		con = c.getComments(blogname)
		return render_to_response("viewcontent.html", {'row':row, 'username':username, 
		'blogname':blogname, 'content':content, 'pubdate':pubdate, 'comments_count':comments_count, 
		'con':con}, 
		context_instance=RequestContext(request)) 
		
def deleteBlog(request):
	username = request.user
	blogname = request.GET.get("blogname")
	Blog.objects.filter(blog_title=blogname).delete()
	blogs = Blog.objects.filter(author=username)
	return render_to_response("view.html", {'username':username, 'blogs':blogs}, 
	context_instance=RequestContext(request))

def editBlog(request):
	username = request.user
	blogname = request.GET.get("blogname")
	b = Blog()
	data = b.getTitleAndContent(blogname)
	return render_to_response("editblog.html", {'username':username, 'data':data, 'blogname':blogname}, 
	context_instance=RequestContext(request))

def updateBlog(request):
	if request.user.is_authenticated():
			username = request.user
			current_title = request.GET.get("blogname")
			new_title = request.POST.get('title')
			new_content = request.POST.get("content")
			b = Blog()
			update = b.updateContent(new_title, new_content, current_title)
			return render_to_response("view.html", context_instance=RequestContext(request))
	else:
			return HttpResponse("Warning: Problem encountered! Unable to update blog.")
			
def addComment(request):
	b = Blog()	
	blogname = request.GET.get("blogname")
	uname = request.POST.get("uname")
	message = 'Login to write your comment.'
	date = datetime.datetime.now()
	blog_content = '/viewblog/content/?blogname=%s' % blogname
	blog_id = b.getBlogId(blogname)
	c = {}
	c.update(csrf(request))
	if request.method == 'POST':
		if User.objects.filter(username = uname).count() == 0:
			return HttpResponse(message)
		else:
			comment_author = uname
			comment_date = date.strftime("%Y-%m-%d %H:%M:%S")
			comment_content = request.POST.get("comments")	
			comments = Comments(comment_author = uname, comment_date = comment_date, comment_content = comment_content, blog_id = blog_id)		
			comments.save()
			return redirect(blog_content)
	else:
		return HttpResponse('Unable to post comment.')
		

	











